package com.huilian.iotbox.admin.controller;

import com.huilian.iotbox.admin.service.AgencyService;
import com.huilian.iotbox.admin.service.RoleService;
import com.huilian.iotbox.admin.service.UserRoleService;
import com.huilian.iotbox.admin.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.controller.BaseController;
import com.huilian.iotbox.data.dto.RoleDto;
import com.huilian.iotbox.data.enums.CommentEnum;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.po.Agency;
import com.huilian.iotbox.data.po.Role;
import com.huilian.iotbox.data.vo.RoleVo;
import com.huilian.iotbox.data.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 少凡
 * @date 2020/3/1 20:23
 */
@Slf4j
@RestController
@RequestMapping("/api/role")
public class RoleController extends BaseController {

    @Resource
    private AgencyService agencyService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Resource
    private UserService userService;

    @GetMapping("/list")
    public ServerResponse list(RoleDto roleDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return ServerResponse.createBySuccess(roleService.findListByAgencyId(userInfo, roleDto));
    }


    @PutMapping
    public ServerResponse update(HttpServletRequest request, @RequestBody Role role) {

        UserInfo userInfo = userService.getLoginUserInfo(request);

        //非1机构人员不能修改超级系统管理员
        if (!userInfo.getAgencyId().equals(1) && role.getId().equals(RoleEnum.SUPER_ADMINISTRATOR.getRoleId())) {
            return ServerResponse.createByErrorMessage("您无权限修改" + RoleEnum.SUPER_ADMINISTRATOR.getRoleName());
        }

        //非1机构人员不能修改公众角色
        if (!userInfo.getAgencyId().equals(1) && role.getAgencyId().equals(0)) {
            return ServerResponse.createByErrorMessage("您无权限修改系统角色");
        }

        return roleService.update(role);
    }

    /**
     * @param roleId 要删除的角色Id
     * @return
     */
    @DeleteMapping("/{roleId}")
    public ServerResponse delete(HttpServletRequest request, @PathVariable Integer roleId) {

        UserInfo userInfo = userService.getLoginUserInfo(request);

        Role role = roleService.getById(roleId);

        //禁止删除系统角色
        if (role.getId().equals(RoleEnum.SUPER_ADMINISTRATOR.getRoleId())) {
            return ServerResponse.createByErrorMessage(RoleEnum.SUPER_ADMINISTRATOR.getRoleName() + "禁止删除!");
        } else if (role.getId().equals(RoleEnum.AGENT.getRoleId())) {
            return ServerResponse.createByErrorMessage(RoleEnum.AGENT.getRoleName() + "禁止删除!");
        } else if (role.getId().equals(RoleEnum.MERCHANT.getRoleId())) {
            return ServerResponse.createByErrorMessage(RoleEnum.MERCHANT.getRoleName() + "禁止删除!");
        }

        //不是1机构的用户，禁止删除公众角色
        if (!userInfo.getAgencyId().equals(1) && role.getAgencyId().equals(0)) {
            return ServerResponse.createByErrorMessage("您无权限删除系统角色");
        }

        Integer count = userRoleService.countByRoleId(role.getId());
        if (count != 0) {
            return ServerResponse.createByErrorMessage("访角色有关联用户，请先移除角色下的用户！");
        }

        return roleService.delete(role.getId());
    }

    /**
     * 添加角色 根据你的权限来
     */
    @PostMapping
    public ServerResponse add(@RequestBody Role role, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        if (RoleEnum.SUPER_ADMINISTRATOR.getRoleId().equals(userInfo.getRoleId())) {
            if (CommentEnum.STATUS_ZERO.getCode().equals(role.getAgencyId())) {
                role.setAgencyId(CommentEnum.STATUS_ZERO.getCode());
            } else {
                role.setAgencyId(userInfo.getAgencyId());
            }
        } else if (!RoleEnum.SUPER_ADMINISTRATOR.getRoleId().equals(userInfo.getRoleId())) {
            role.setAgencyId(userInfo.getAgencyId());
        } else {
            return ServerResponse.createByErrorMessage("用户权限不足!");
        }

        if(StringUtils.isEmpty(role.getName()) || StringUtils.isEmpty(role.getAgencyId())){
            return ServerResponse.createByErrorMessage("机构号和角色名称都不能为空!");
        }

        return roleService.add(role);
    }

    /**
     * 添加用户时，分配角色
     *
     * @param userId
     * @return
     */
    @GetMapping("/assignRoles")
    public ServerResponse assignRoles(HttpServletRequest request, @RequestParam(required = false) String userId) {

        UserInfo userInfo = userService.getLoginUserInfo(request);

        return roleService.assignRoles(userInfo, userId);
    }

    /***
     * 角色分配：显示除超级管理员，代理商，商家，三个角色外的公共角色，和自已机构的角色
     */
    @GetMapping("/getUserRoleInfo")
    public ServerResponse getUserRoleInfo(HttpServletRequest request) {
        /**这个map存储返回信息 因为每个权限有每个权限的不一样特有的地方*/
        Map<String, Object> resultMap = new HashMap<>();
        UserInfo userInfo = userService.getLoginUserInfo(request);
        RoleVo roleVo = new RoleVo();
        roleVo.setUserInfo(userInfo);

        //读取当前用户权限判断是不是商家或者管理员或合作伙伴
        if (RoleEnum.SUPER_ADMINISTRATOR.getRoleId().equals(userInfo.getRoleId())) {
            roleVo.setRoleId(RoleEnum.SUPER_ADMINISTRATOR.getRoleId());
            List<Agency> agencyList = agencyService.findAgencyIdAndName(roleVo.getUserInfo().getAgencyId());
            resultMap.put("agencyList", agencyList);
        } else if (RoleEnum.AGENT.getRoleId().equals(userInfo.getRoleId())) {
            roleVo.setRoleId(RoleEnum.AGENT.getRoleId());
            List<Agency> agencyList = agencyService.findAgencyIdAndName(roleVo.getUserInfo().getAgencyId());
            resultMap.put("agencyList", agencyList);
        } else if (RoleEnum.MERCHANT.getRoleId().equals(userInfo.getRoleId())) {
        } else {
            return ServerResponse.createByErrorMessage("用户权限不足!");
        }
        resultMap.put("roleList", roleService.getRoleByAgencyId(roleVo));

        return ServerResponse.createBySuccess(resultMap);
    }
}
